const { createLogger } = require('./logger');
const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');
dayjs.extend(utc);
dayjs.extend(timezone);
const CHINA_TZ = 'Asia/Shanghai';
function chinaNow() { return dayjs().tz(CHINA_TZ).format('YYYY-MM-DD HH:mm:ss'); }

// 创建日志记录器
const logger = createLogger('ws-helper');

/**
 * 创建WebSocket助手
 * @param {object} namespace Socket.IO命名空间
 * @returns {object} WebSocket助手对象
 */
function createWebSocketHelper(namespace) {
  if (!namespace) {
    logger.warn('创建WebSocket助手时没有提供命名空间');
    return {
      sendToRoom: () => {},
      sendToAll: () => {},
      sendDeployStart: () => {},
      sendDeployLog: () => {},
      sendDeployProgress: () => {},
      sendDeployComplete: () => {},
      sendDeployError: () => {},
      sendBatchDeployStart: () => {},
      sendBatchDeployComplete: () => {}
    };
  }
  
  return {
    /**
     * 向房间发送消息
     * @param {string} room 房间ID
     * @param {string} event 事件名称
     * @param {object} data 事件数据
     */
    sendToRoom(room, event, data) {
      if (!room) {
        namespace.emit(event, data);
      } else {
        namespace.to(room).emit(event, data);
      }
    },
    
    /**
     * 向所有客户端发送消息
     * @param {string} event 事件名称
     * @param {object} data 事件数据
     */
    sendToAll(event, data) {
      namespace.emit(event, data);
    },
    
    /**
     * 发送部署开始事件
     * @param {string} deployId 部署ID
     * @param {string} appName 应用名称
     * @param {object} storageConfig 存储配置
     */
    sendDeployStart(deployId, appName, storageConfig) {
      namespace.emit('deployStart', {
        deployId,
        appName,
        storageConfigId: storageConfig.id,
        storageConfigName: storageConfig.name,
        status: 'deploying',
        timestamp: chinaNow()
      });
    },
    
    /**
     * 发送部署日志事件
     * @param {string} deployId 部署ID
     * @param {string} appName 应用名称
     * @param {string} log 日志内容
     * @param {string} level 日志级别
     */
    sendDeployLog(deployId, appName, log, level = 'info') {
      namespace.emit('deployLog', {
        deployId,
        appName,
        log,
        level,
        timestamp: chinaNow()
      });
    },
    
    /**
     * 发送部署进度事件
     * @param {string} deployId 部署ID
     * @param {string} appName 应用名称
     * @param {number} progress 进度百分比
     * @param {string} currentFile 当前文件
     * @param {number} uploadedFiles 已上传文件数
     * @param {number} totalFiles 总文件数
     */
    sendDeployProgress(deployId, appName, progress, currentFile, uploadedFiles, totalFiles) {
      namespace.emit('deployProgress', {
        deployId,
        appName,
        progress,
        currentFile,
        uploadedFiles,
        totalFiles,
        timestamp: chinaNow()
      });
    },
    
    /**
     * 发送部署完成事件
     * @param {string} deployId 部署ID
     * @param {string} appName 应用名称
     * @param {object} storageConfig 存储配置
     * @param {string} deployPath 部署路径
     * @param {string} publicPath 公共路径
     */
    sendDeployComplete(deployId, appName, storageConfig, deployPath, publicPath) {
      namespace.emit('deployComplete', {
        deployId,
        appName,
        storageConfigId: storageConfig.id,
        storageConfigName: storageConfig.name,
        deployPath,
        publicPath,
        status: 'success',
        timestamp: chinaNow()
      });
    },
    
    /**
     * 发送部署错误事件
     * @param {string} deployId 部署ID
     * @param {string} appName 应用名称
     * @param {Error} error 错误对象
     */
    sendDeployError(deployId, appName, error) {
      namespace.emit('deployError', {
        deployId,
        appName,
        error: error.message || String(error),
        status: 'failed',
        timestamp: chinaNow()
      });
    },
    
    /**
     * 发送批量部署开始事件
     * @param {string} deployId 部署ID
     * @param {string[]} apps 应用列表
     */
    sendBatchDeployStart(deployId, apps) {
      namespace.emit('batchDeployStart', {
        deployId,
        apps,
        status: 'start',
        message: '开始批量部署应用...',
        timestamp: chinaNow()
      });
    },
    
    /**
     * 发送批量部署完成事件
     * @param {string} deployId 部署ID
     * @param {object[]} results 部署结果
     * @param {object} storageConfig 存储配置
     */
    sendBatchDeployComplete(deployId, results, storageConfig) {
      namespace.emit('batchDeployComplete', {
        deployId,
        apps: results,
        status: 'success',
        message: '批量部署完成',
        details: {
          storageType: storageConfig.type,
          successCount: results.filter(r => r.success).length,
          failCount: results.filter(r => !r.success).length
        },
        timestamp: chinaNow()
      });
    }
  };
}

module.exports = {
  createWebSocketHelper
}; 